package com.fishingwithme.android.ui.screens.my.settings

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ChevronRight
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import coil.compose.rememberAsyncImagePainter
import com.fishingwithme.android.R
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.screens.my.MyScreenHiltEntryPoint
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.AuthViewModel
import dagger.hilt.android.EntryPointAccessors

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(navController: NavController) {
    val context = LocalContext.current
    val preferencesManager = EntryPointAccessors.fromApplication(
        context.applicationContext,
        MyScreenHiltEntryPoint::class.java
    ).preferencesManager()

    val user by preferencesManager.getLoginUserObj().collectAsState(initial = null)

    // Get AuthViewModel for logout functionality
    val authViewModel: AuthViewModel = hiltViewModel()


    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(R.string.profile)) },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(
                            Icons.Default.ArrowBack,
                            contentDescription = stringResource(R.string.back)
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(AppDimensions.SPACING_16)
        ) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_24),
                elevation = CardDefaults.cardElevation(defaultElevation = AppDimensions.CARD_ELEVATION_2)
            ) {
                Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = AppDimensions.SPACING_8),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Box(
                            modifier = Modifier
                                .size(AppDimensions.ICON_SIZE_60)
                                .clip(RoundedCornerShape(AppDimensions.ROUNDED_CORNER_50))
                                .clickable {
                                    navController.navigate(FishingNavigation.USER_EDIT)
                                }
                                .background(MaterialTheme.colorScheme.primary),
                            contentAlignment = Alignment.Center
                        ) {
                            Image(
                                painter = rememberAsyncImagePainter(user?.avatarUrl),
                                contentDescription = "User Avatar",
                                modifier = Modifier.fillMaxSize(),
                                contentScale = ContentScale.Crop
                            )
                        }

                        Spacer(modifier = Modifier.width(AppDimensions.SPACING_16))

                        Column {
                            Text(
                                text = user?.nickname ?: stringResource(R.string.username),
                                style = MaterialTheme.typography.titleMedium
                            )
                            Text(
                                text = user?.username ?: "",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_24),
                elevation = CardDefaults.cardElevation(defaultElevation = AppDimensions.CARD_ELEVATION_2)
            ) {
                Column {
                    SettingsItem(
                        title = stringResource(R.string.theme_settings),
                        onClick = {
                            navController.navigate(FishingNavigation.THEME_SETTINGS)
                        }
                    )
                    Divider(modifier = Modifier.fillMaxWidth())
                    SettingsItem(
                        title = stringResource(R.string.fisher_center),
                        onClick = {
                            navController.navigate(FishingNavigation.MAINTAINER_CENTER)
                        }
                    )

                    Divider(modifier = Modifier.fillMaxWidth())
                    SettingsItem(
                        title = stringResource(R.string.settings_agreement),
                        onClick = {
                            navController.navigate("${FishingNavigation.AGREEMENT_POLICY}?type=AD_UA")
                        }
                    )

                    Divider(modifier = Modifier.fillMaxWidth())

                    SettingsItem(
                        title = stringResource(R.string.settings_policy),
                        onClick = {
                            navController.navigate("${FishingNavigation.AGREEMENT_POLICY}?type=AD_PP")
                        }
                    )
                    Divider(modifier = Modifier.fillMaxWidth())

                    SettingsItem(
                        title = stringResource(R.string.logout),
                        onClick = {
                            // Implement logout functionality
                            authViewModel.logout()
                            // Navigate to login screen
                            navController.navigate(FishingNavigation.LOGIN) {
                                // Clear the back stack so user can't go back to main app without logging in
                                popUpTo(0) { inclusive = true }
                            }
                        }
                    )
                }
            }
        }
    }
}

@Composable
private fun SettingsItem(
    title: String,
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(AppDimensions.SPACING_16),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = title,
            style = MaterialTheme.typography.bodyMedium
        )
        Spacer(modifier = Modifier.weight(1f))
        Icon(
            imageVector = Icons.Default.ChevronRight,
            contentDescription = "Navigate",
            tint = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}